package xkp.lesson.store.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import xkp.lesson.store.Config;
import xkp.lesson.store.R;
import xkp.lesson.store.entity.JsonData;
import xkp.lesson.store.entity.UserInfo;
import xkp.lesson.store.utils.HttpUtils;

public class LoginActivity extends BaseActivity {

    private EditText userNameEdit, userPwdEdit,tryCodeEdit;
    private ImageView tryCodeImg;
    private Button tryCodeBtn;
    private CheckBox remberMeCheckBox;
    private Button logBtn;
    private String url = Config.BASE_URL + "/defaultKaptcha?d=";
    private OkHttpClient mOkHttpClient = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();



    }

    private void initView() {
        userNameEdit = findViewById(R.id.userNameEdit);
        userPwdEdit = findViewById(R.id.userPwdEdit);
        tryCodeEdit = findViewById(R.id.tryCodeEdit);
        tryCodeImg = findViewById(R.id.tryCodeImg);
        tryCodeBtn = findViewById(R.id.tryCodeBtn);

        long time = System.currentTimeMillis();
        String newURL = url+time;

        tryCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               loadTryCodeImg();
            }
        });
        logBtn = findViewById(R.id.logBtn);

        loadTryCodeImg();
        logBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 String usercode = tryCodeEdit.getText().toString();;
                 String username = userNameEdit.getText().toString();
                 String userpwd = userPwdEdit.getText().toString();
                 login(username,userpwd,usercode);
            }
        });

    }

    private void loadTryCodeImg(){

        String defaultKaptchaURL  = url+System.currentTimeMillis();
        final Request request = new Request.Builder()
                .url(defaultKaptchaURL)
                .get()
                .addHeader("mobile", "mobile")
                .build();
        mOkHttpClient = HttpUtils.getClient();
        //mOkHttpClient = new OkHttpClient();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final byte[] img = response.body().bytes();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
                        //通过imageview，设置图片
                        tryCodeImg.setImageBitmap(bitmap);

                    }
                });
            }

        });
    }

    private void login(String username, String userpwd,String usercode ) {
        String userName = userNameEdit.getText().toString();
        String userPwd = userPwdEdit.getText().toString();
        String tryCode = tryCodeEdit.getText().toString();
      
        RequestBody formBody = new FormBody.Builder()
                .add("userName", username)
                .add("userPwd", userpwd)
                .add("tryCode", usercode)
                .build();
        final Request request = new Request.Builder()
                .url(Config.BASE_URL + "/userInfo/login")
                .post(formBody)
                .addHeader("mobile", "mobile")
                .build();
        mOkHttpClient = HttpUtils.getClient();
        //mOkHttpClient = new OkHttpClient();
        Call call = mOkHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                final JsonData<UserInfo> jsonData = JSON.parseObject(str, new TypeReference<JsonData<UserInfo>>() {});
                if(jsonData.getCode() == -1){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), jsonData.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }else{
                    Config.token = jsonData.getData().getToken();
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }



            }

        });
    }
}
